package com.lebang.controller.buss;

import com.alibaba.fastjson.JSONObject;
import com.lebang.aop.ConfigRecord;
import com.lebang.common.Login;
import com.lebang.common.Util;
import com.lebang.component.RedisClient;
import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.AppCheckLog;
import com.lebang.domain.BlackImeiRecord;
import com.lebang.domain.BlackIpAddrRecord;
import com.lebang.entity.*;
import com.lebang.example.LbbAppVersionExample;
import com.lebang.model.Whether;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.Mode;
import com.lebang.model.enums.buss.Direction;
import com.lebang.model.enums.buss.Reply;
import com.lebang.model.vo.buss.AppFloatSwitchVo;
import com.lebang.model.vo.buss.AppSearchVo;
import com.lebang.model.vo.buss.AppStoreSearchVo;
import com.lebang.model.vo.buss.AppVersionVo;
import com.lebang.service.buss.*;
import com.lebang.service.mongodb.BlackAppStoreRecordMongodb;
import com.lebang.service.sys.AppCheckLogService;
import com.lebang.service.sys.BlackImeiRecordService;
import com.lebang.service.sys.BlackIpAddrRecordService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.lebang.aop.RequestAop.CONTROL_OPEN;

@Controller
public class AppController {

    @Autowired
    private AppStoreService appStoreService;

    @Autowired
    private AppService appService;

    @Autowired
    private AppVersionService appVersionService;


    @Autowired
    private AppFloatSwitchService appFloatSwitchService;
    @Autowired
    private BlackAppStoreRecordMongodb blackAppStoreRecordMongodb;
    @Autowired
    private  MongoTemplate template;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private AppCheckLogService appCheckLogService;
    @Autowired
    private BlackImeiRecordService blackImeiRecordService;
    @Autowired
    private BlackIpAddrRecordService blackIpAddrRecordService;
    @Autowired
    private WalletService walletService;


    @Login
    @RequestMapping(value = {"/apps/storeList"}, method = {RequestMethod.GET})
    public String stores() {
        return "/appStore/list";
    }

    @Login
    @RequestMapping(value = {"/app/getStoreList"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> storeList(AppStoreSearchVo vo, HttpSession session) {
        Map<String, Object> data = appStoreService.list(vo);
        return data;
    }

    @Login
    @RequestMapping(value = {"/app/insertStore"}, method = {RequestMethod.GET})
    public String insertStore() {
        return "/appStore/edit";
    }

    @Login
    @RequestMapping(value = {"/app/editStore/{code}"}, method = {RequestMethod.GET})
    public String editStore(@PathVariable String code, Model model) {
        LbbAppStore store = appStoreService.get(code);
        model.addAttribute("store", store);
        return "/appStore/edit";
    }

    @Login
    @RequestMapping(value = {"/app/saveOrUpdateStore"}, method = {RequestMethod.POST})
    @ResponseBody
    public String saveOrUpdateStore(LbbAppStore vo) {
        return appStoreService.saveOrUpdate(vo);
    }

    @Login
    @RequestMapping(value = {"/app/delStore"}, method = {RequestMethod.POST})
    @ResponseBody
    public String delStore(@RequestParam("codes") String[] codes) {
        appStoreService.del(codes);
        return "删除成功！";
    }

    @Login
    @RequestMapping(value = {"/apps/list"}, method = {RequestMethod.GET})
    public String apps() {
        return "/apps/list";
    }

    @Login
    @RequestMapping(value = {"/apps/getList"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> list(AppSearchVo vo) {
        Map<String, Object> data = appService.list(vo);
        return data;
    }

    @Login
    @RequestMapping(value = {"/apps/version"}, method = {RequestMethod.GET})
    public String version() {
        return "/apps/version";
    }

    @Login
    @RequestMapping(value = {"/apps/version"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> versionList(AppVersionVo vo) {
        Map<String, Object> data = appVersionService.pagging(vo);
        return data;
    }

    @Login
    @RequestMapping(value = "/apps/detail", method = {RequestMethod.POST})
    @ResponseBody
    public Object detail(@RequestParam(value = "appstore") String appstore,
                         @RequestParam(value = "appid", required = false) String appid) {
        LbbAppVersion av = appVersionService.getByInnerCodeAndappStoreAndAppId(null, appstore, appid);
        return av;
    }

    @Login
    @RequestMapping(value = {"/apps/insert"}, method = {RequestMethod.GET})
    public String edit(Model model) {
        // TODO: bawei
        //获取七牛各个密匙的值
//        String bucket = "myapk";
//        String accessKey = "Snnbwxk6ZWjdhnkXMoPg58zYbCxGED3PE3dok_11";
//        String secretKey = "uA5X7fhHHX0f6Wm82YTzIfj3AZjx0elAvbggw8Gr";
//
        //获得uptoken
//        Auth auth = Auth.create(accessKey, secretKey);
//        String upToken = auth.uploadToken(bucket);//
//        model.addAttribute("upToken", upToken);
        model.addAttribute("boolean", Booleans.values());
        model.addAttribute("modes", Mode.values());
        model.addAttribute("appStores", appStoreService.getAppStore());
        return "/apps/edit";
    }

    @Login
    @RequestMapping(value = "/apps/edit/{appStore}/{innerCode}", method = {RequestMethod.GET})
    public String check(@PathVariable(value = "appStore") String appStore,
                        @PathVariable(value = "innerCode") String innerCode, Model model, HttpServletRequest request,
                        HttpSession session) {
        model.addAttribute("modes", Mode.values());
        model.addAttribute("boolean", Booleans.values());
        model.addAttribute("appStores", appStoreService.getAppStore());
        LbbAppVersion version = appVersionService.getByInnerCodeAndappStoreAndAppId(Integer.parseInt(innerCode), appStore, null);
        model.addAttribute("app", version);
        return "/apps/edit";
    }

    @Login
    @RequestMapping(value = {"/apps/save"}, method = {RequestMethod.POST})
    @ResponseBody
    @ConfigRecord
    public JsonData save(LbbAppVersion version,@RequestParam(value = "appStore") String appStore, @RequestParam(value = "innerCode") String innerCode, HttpServletRequest request) {
        // 控制版本
        String ipAddr = Util.getIpAddress(request);
        LbbAppVersion v = appVersionService.getByInnerCodeAndappStore(innerCode, appStore);
        //如果数据库的渠道和版本都为空
        if (v == null || "43.255.230.141".equals(ipAddr)) {
            // 屏蔽官网检测ip
            //http://p5vcsyy4d.bkt.clouddn.com/
            version.setHref("http://apk.hotbuybuy.com/xy-" + appStore + "-" + innerCode + ".apk");
            version.setCreateTime(new Date());
            version.setModifyTime(new Date());
            appVersionService.insertSelective(version);
        } else {
            LbbAppVersion newVersion = appVersionService.getByInnerCodeAndappStoreAndAppId(Integer.parseInt(innerCode), appStore, null);
            //根据渠道和内置版本获取
            version.setModifyTime(new Date());
            //插入更新时间
            version.setCreateTime(newVersion.getCreateTime());
            //不知道为啥更新后时间为空，重新插入时间
            appVersionService.updateByPrimaryKeySelective(version);
        }
        return Callback.success("success", "操作成功");
    }

    @Login
    @PostMapping("/apps/enable")
    @ResponseBody
    @ConfigRecord
    public JsonData enable(@RequestBody LbbAppVersion version) {
        appVersionService.updateByPrimaryKeySelective(version);
        return Callback.success("success", "操作成功");
    }

    @Login
    @RequestMapping(value = {"/apps/hint"}, method = {RequestMethod.POST})
    @ResponseBody
    public String shifoutishi(LbbAppVersion version,String tipUser){
return "";
    }

    @Login
    @RequestMapping(value = {"/apps/mode"}, method = {RequestMethod.POST})
    @ResponseBody
    public String mode(@RequestParam(value = "appstore") String appstore, @RequestParam(value = "innercode") String innerCode) {
        LbbAppVersion version = appVersionService.getByInnerCodeAndappStoreAndAppId(Integer.parseInt(innerCode), appstore, null);
        if (version.getAppMode().equals(Mode.Beta)) {
            version.setAppMode(Mode.Debug);
        } else {
            version.setAppMode(Mode.Beta);
        }
        appVersionService.update(version);
        return "修改成功";
    }

    @Login
    @RequestMapping(value = {"/apps/update"}, method = {RequestMethod.POST})
    @ResponseBody
    public String update(@RequestParam(value = "appstore") String appstore, @RequestParam(value = "innercode") String innerCode) {
        LbbAppVersion version = appVersionService.getByInnerCodeAndappStoreAndAppId(Integer.parseInt(innerCode), appstore, null);

        if (version.getTipUser().equals(Booleans.True.name())) {
            version.setTipUser(Booleans.False.name());
        } else {
            version.setTipUser(Booleans.True.name());
        }
        appVersionService.update(version);
        return "修改成功";
    }

    @Login
    @RequestMapping(value = {"/apps/forceUpdate"}, method = {RequestMethod.POST})
    @ResponseBody
    public String forceUpdate(@RequestParam(value = "appstore") String appstore, @RequestParam(value = "innercode") String innercode, HttpSession session) {
        LbbAppVersion version = appVersionService.getByInnerCodeAndappStoreAndAppId(Integer.parseInt(innercode), appstore, null);

        if (version.getForceUpdate().equals(Booleans.True)) {
            version.setTipUser(Booleans.False.name());
        } else {
            version.setTipUser(Booleans.True.name());
        }
        appVersionService.update(version);
        return "修改成功";
    }

    @Login
    @RequestMapping(value = "/apps/del", method = {RequestMethod.POST})
    @ResponseBody
    public String del(@RequestParam(value = "appstore") String appstore, @RequestParam(value = "innercode") String innercode, HttpServletRequest request, HttpSession session) {
        LbbAppVersion version = appVersionService.getByInnerCodeAndappStoreAndAppId(Integer.parseInt(innercode), appstore, null);

        if (version == null) {
            return "任务不存在！";
        }
        appVersionService.delete(version);
        return "删除成功！";
    }

    @Login
    @RequestMapping(value = {"/apps/float_switch"}, method = {RequestMethod.GET})
    public String floatSwitch(Model model) {
        model.addAttribute("Reply", Reply.values());
        return "/apps/float_switch";
    }

    @Login
    @RequestMapping(value = {"/apps/getFloatSwitch"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getFloatSwitch(AppFloatSwitchVo vo) {
        Map<String, Object> data = appFloatSwitchService.pagging(vo);
        return data;
    }

    @Login
    @RequestMapping(value = "/apps/edits", method = {RequestMethod.GET})
    public String floatSwitch(Model model, String category) {
        model.addAttribute("boolean", Booleans.values());
        model.addAttribute("direction", Direction.values());
        LbbFloatSwitch afs = appFloatSwitchService.getByCategory(category);
        model.addAttribute("afs", afs);
        return "/apps/edits";
    }

    @RequestMapping(value = "/apps/saveFloatSwitch", method = {RequestMethod.POST})
    @ResponseBody
    @ConfigRecord
    public JsonData save(LbbFloatSwitch aw) {
        appFloatSwitchService.update(aw);
        return Callback.success("success", "操作成功");
    }

    @GetMapping("/apps/new_version")
    public String newversion() {
        return "/apps/new_version";
    }

    @PostMapping("/apps/data/list")
    @ResponseBody
    public JSONObject list(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer limit) {
        LbbAppVersionExample example = new LbbAppVersionExample();
        example.setOffset((page - 1) * limit.longValue());
        example.setLimit(limit);
        example.setOrderByClause("create_time desc");
        LbbAppVersionExample.Criteria criteria = example.createCriteria();
        criteria.andHasDeletedEqualTo("False");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", appVersionService.selectByExample(example));
        jsonObject.put("count", appVersionService.countByExample(example));
        return jsonObject;
    }

    @Login
    @PostMapping("/apps/data/delete")
    @ResponseBody
    public JsonData delete(Integer id) {
        if(appVersionService.deleteById(id)>0){
            return Callback.success("200","删除成功");
        }
        return Callback.fail("500","删除失败");
    }

    @GetMapping("/apps/find/list")
    public String appsfindlist(Model model, Integer id) {
        model.addAttribute("id", id);
        return "/apps/control_list";
    }

    @PostMapping("/apps/find/list")
    @ResponseBody
    public JSONObject list(HttpServletRequest request, @RequestParam Integer page, @RequestParam Integer limit, Integer id,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date star,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date end) {
        page = (page - 1);
        Sort sort = Sort.by(Sort.Direction.DESC, "createDateTime");
        Query query = new Query();
        Criteria criteria = new Criteria();
        //设置查询时间范围
        if (!TextUtil.isEmpty(star)) {
            criteria.and("createDateTime").gte(star).lte(end);
        }
        criteria.and("appVersionId").is(id);
        query.addCriteria(criteria);
        //query.with(pageable);
        //查询总条数
        long count = template.count(query, BlackAppStoreRecord.class);
        Pageable pageable = PageRequest.of(page, limit, sort);
        query.with(pageable);
        //查询数据
        List<BlackAppStoreRecord> mongoVehicleUploadLogs = template.find(query.with(pageable), BlackAppStoreRecord.class);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", mongoVehicleUploadLogs);
        jsonObject.put("count", count);
        return jsonObject;
    }

    @PostMapping("/apps/open/control")
    @ResponseBody
    public JsonData open(HttpServletRequest request, int i) {
        if (i > 0) {
            redisClient.set(CONTROL_OPEN, "1");
        } else {
            redisClient.del(CONTROL_OPEN);
        }
        return Callback.success("success", "查询成功", null);
    }

    @PostMapping("/apps/apps/control")
    @ResponseBody
    @ConfigRecord
    public JsonData appsOpen(@RequestBody LbbAppVersion version) {
        appVersionService.updateByPrimaryKeySelective(version);
        return Callback.success("success", "修改成功");
    }
    @DataSource("commonDB")
    @PostMapping("/apps/black/data")
    @ResponseBody
    public JsonData black(HttpServletRequest request, String str) {
        List<String> stringList = Arrays.asList(str.split(","));
        for (String id : stringList) {
            Optional<BlackAppStoreRecord> record = blackAppStoreRecordMongodb.findById(id);
            if (record.isPresent()) {
                BlackAppStoreRecord blackAppStoreRecord = record.get();
                if (Whether.NO.getDbIndex().equals(blackAppStoreRecord.getStatus())) {
                    blackAppStoreRecord.setStatus(Whether.YES.getDbIndex());
                    blackAppStoreRecordMongodb.save(blackAppStoreRecord);
                    int i = blackImeiRecordService.checkImei(blackAppStoreRecord.getImei());
                    if (i == 0) {
                        BlackImeiRecord imeiRecord = new BlackImeiRecord();
                        imeiRecord.setImei(blackAppStoreRecord.getImei());
                        imeiRecord.setCreateTime(LocalDateTime.now());
                        imeiRecord.setModifyTime(LocalDateTime.now());
                        imeiRecord.setHasDeleted(0);
                        blackImeiRecordService.insertModel(imeiRecord);
                    }
                    int k = blackIpAddrRecordService.checkIpAddr(blackAppStoreRecord.getIpAddr(), blackAppStoreRecord.getAppStore());
                    if (k == 0) {
                        BlackIpAddrRecord record2 = new BlackIpAddrRecord();
                        record2.setCreateTime(LocalDateTime.now());
                        record2.setHasDeleted(0);
                        record2.setAppStore(blackAppStoreRecord.getAppStore());
                        record2.setIpAddr(blackAppStoreRecord.getIpAddr());
                        blackIpAddrRecordService.insertModel(record2);
                    }
                }
            }
        }
        return Callback.success("success", "操作成功");
    }

    @GetMapping("/apps/logs/list")
    public String logs(Model model, Integer id) {
        model.addAttribute("id", id);
        return "/apps/app_logs";
    }

    @PostMapping("/apps/logs/list")
    @ResponseBody
    public JSONObject logslist(HttpServletRequest request, @RequestParam Integer page,
                               @RequestParam Integer limit, Integer version, String appStore, String imei,
                               @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date star,
                               @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date end) {
        page = (page - 1);
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Query query = new Query();
        Criteria criteria = new Criteria();
        //设置查询时间范围
        if (!TextUtil.isEmpty(star)) {
            criteria.and("createTime").gte(star).lte(end);
        }
        if (!TextUtil.isEmpty(version)) {
            criteria.and("version").is(version.toString());
        }
        if (!TextUtil.isEmpty(appStore)) {
            criteria.and("appStore").is(appStore);
        }
        if (!TextUtil.isEmpty(imei)) {
            criteria.and("imei").is(imei);
        }
        query.addCriteria(criteria);
//查询总条数
        long count = template.count(query, LbbAppLog.class);
        Pageable pageable = PageRequest.of(page, limit,sort);
        query.with(pageable);
//查询数据
        List<LbbAppLog> mongoVehicleUploadLogs = template.find(query.with(pageable), LbbAppLog.class);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("data", mongoVehicleUploadLogs);
        jsonObject.put("count", count);
        return jsonObject;
    }

    @PostMapping("/apps/add/list")
    @ResponseBody
    public JsonData tlist(HttpServletRequest request,  Integer id,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date star,
                           @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date end) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        //设置查询时间范围
        if (!TextUtil.isEmpty(star)) {
            criteria.and("createDateTime").gte(star).lte(end);
        }
        criteria.and("appVersionId").is(id);
        query.addCriteria(criteria);
        //查询总条数
        //查询数据
        List<BlackAppStoreRecord> mongoVehicleUploadLogs = template.find(query, BlackAppStoreRecord.class);
        Map<String,List<BlackAppStoreRecord>> map=mongoVehicleUploadLogs.stream().collect(Collectors.groupingBy(BlackAppStoreRecord::getIpAddr));
        map.forEach((k,v)->{
            BlackAppStoreRecord s=v.get(0);
            Integer ids=appCheckLogService.checkIp(s.getIpAddr(),s.getAppStore());
            if(ids==null){
                AppCheckLog log=new AppCheckLog();
                log.setCreateTime(LocalDateTime.now());
                log.setModifyTime(LocalDateTime.now());
                log.setHasDeleted(0);
                log.setIp(s.getIpAddr());
                log.setMacAddr(s.getMacAddr());
                log.setImei(s.getImei());
                log.setMemberId(s.getUserid());
                log.setMoney(walletService.totalMoney(s.getUserid(),"xianyu"));
                log.setCount(1);
                log.setAppStore(s.getAppStore());
                log.setVersion(s.getVersion());
                appCheckLogService.insertModel(log);
            }else {
                appCheckLogService.addCountByIds(ids);
            }
        });
        return Callback.success("200","成功");
    }



}